import dayjs from 'dayjs';
import tip from '@/utils/util.tip';
import { defineStore } from 'pinia';
import { v4 as uuidv4 } from 'uuid';
import type { Note, NoteList } from '@/types';
import { localStorageGet, localStorageSet } from '@/utils/util.localStorage';

export const useNoteStore = defineStore('note', () => {
	// 当前正在打开的笔记
	const activeNote = ref<Note>({
		id: '',
		title: '',
		content: '',
		createTime: '',
		updateTime: '',
	});
	watch(
		activeNote,
		(val: Note) => {
			// 监听 activeNote 变化，并自动保存更改
			if (editorStatus.value === 'edit') {
				if (val.title.trim().length < 1) {
					tip.error('标题不能为空');
					return;
				}
				updateNote();
			}
		},
		{ deep: true }
	);

	// 当前编辑器状态
	const editorStatus = ref<'edit' | 'create'>('create');

	// 笔记列表
	const noteList = ref<NoteList>([]);
	watch(
		noteList,
		(val: NoteList) => {
			// 监听 noteList 变化，并将其存储到 localStorage 中
			localStorageSet('noteList', JSON.stringify(val));
		},
		{ deep: true }
	);

	// 创建笔记
	const createNote = (note: { title: string; content: string }): void => {
		noteList.value.unshift({
			...note,
			id: uuidv4(),
			createTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
			updateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
		});
		editorStatus.value = 'edit';
		activeNote.value = noteList.value[0];
		tip.success('笔记创建成功');
	};

	// 删除笔记
	const deleteNode = (id: string): void => {
		if (id.trim().length < 1) {
			tip.error('笔记不存在');
			return;
		}
		noteList.value = noteList.value.filter((item) => item.id !== id);
		if (id === activeNote.value.id) {
			// 如果删除的是当前正在打开的笔记，则切换到编辑器状态到 'create'
			editorStatus.value = 'create';
		}
		tip.success('笔记删除成功');
	};

	// 更新笔记
	const updateNote = (): void => {
		const index = noteList.value.findIndex((item) => item.id === activeNote.value.id);
		if (index !== -1) {
			noteList.value[index] = {
				...activeNote.value,
				title: activeNote.value.title,
				content: activeNote.value.content,
				updateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
			};
			editorStatus.value = 'edit';
		}
	};

	onBeforeMount(() => {
		// 从 localStorage 中获取 noteList
		const noteListStr = localStorageGet('noteList');
		if (noteListStr) {
			noteList.value = JSON.parse(noteListStr);
		}
	});

	return {
		noteList,
		activeNote,
		editorStatus,
		updateNote,
		createNote,
		deleteNode,
	};
});
